/**
 * 
 * Code: 200, Message: "OK"
  Code: 500, Message: "系统错误"
  Code: 500, Message: "系统错误"
  Code: 500, Message: "系统错误"
  Code: 422, Message: "请求参数错误"
  Code: 422, Message: "请求参数错误"
  Code: 401, Message: "登录时效已过期，请重新登录"
  Code: 3000, Message: "系统错误"
  Code: 3001, Message: "系统错误"
 * 
 */
import env from './env'
import util from './../utils/util'

const http = ({
    method,
    url,
    data
  }) => {
  return new Promise(async (resolve, reject) => {
    let token = "";
    let header = {
      'content-type': 'application/json',
      // 'Authorization': `Bearer ${token}`
    };

    data = Object.assign({}, data, {
      pver: env.pver,
      ver: env.ver,
    });

    wx.request({
      url: `${env.baseUrl}${url}`,
      method: method,
      data: util.getSignParams(data),
      header: header,
      success(res) {
        //请求成功
        //判断状态码---errno状态根据后端定义来判断
        if (!res.data.errno) {
          resolve(res.data);
        } else if (res.data.errno === 401) {
          wx.clearStorageSync();
        } else {
          //其他异常
          wx.showToast({
            title: res.data.msg || '运行时错误,请稍后再试',
            icon: 'error',
            duration: 2000
          })
          reject(res.data)      
        }
      },
      fail(err) {
        //请求失败
        reject(err)
      }
    })
  });
};

//查看
http.get = (url, data = {}) => http({
  method: 'get',
  url,
  data
})

//创建
http.post = (url, data = {}) => http({
  method: 'post',
  url,
  data
})

//编辑
http.put = (url, data = {}) => http({
  method: 'put',
  url,
  data
})

//删除
http.delete = (url, data = {}) => http({
  method: 'delete',
  url,
  data
})

export default http